<template>
  <div class="Users">
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home' }">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 视图区 -->
    <el-card class="box-card" >
      <!-- 搜索与添加区域 -->
      <div style="margin-top: 15px">
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :span="7">
            <el-input
              placeholder="请输入用户名"
              v-model="queryInfo.query"
              clearable
              @clear="queryUser"
            >
              <template #append
                ><el-button
                  icon="el-icon-search"
                  @click="queryUser"
                ></el-button>
              </template> </el-input
          ></el-col>
          <!-- 第二列 -->
          <el-col :span="4">
            <el-button type="primary" @click="dialogVisible = true"
              >添加用户</el-button
            >
          </el-col>
        </el-row>
      </div>

      <!-- 表格区域 -->

      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="ID"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号码"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <!-- 开关 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template #default="scope">
            <!-- 修改 -->

            <el-tooltip
              class="item"
              effect="dark"
              content="修改信息"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id, scope.row.username)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色 -->

            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      v-model="dialogVisible"
      width="30%"
      @close="addDialogClose"
    >
      <!-- 添加用户的表单 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="70px"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改用户信息的对话框 -->
    <el-dialog
      title="修改用户信息"
      v-model="editDialogVisible"
      width="50%"
      @close="editDiologClose"
    >
      <!-- 修改用户消息的表单 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="70px"
        :rules="editFormRules"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserinfo">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" v-model="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户: {{ userInfo.username }}</p>
        <p>当前的角色: {{ userInfo.role_name }}</p>

        <p>
          分配新角色
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  upDateUserList,
  addUser_axios,
  changeUserInfo,
  upDataChange,
  removeUser,
  saveRoleInfo,
} from "@/network/User.js";
export default {
  name: "Users",
  data() {
    //自定义的邮箱和手机号校验规则,使用正则表达式进行
    // var checkEmail = (rule, value, cb)=>{}
    // var checkMobile = ()=>{}
    return {
      userInfo: {}, //角色信息
      roleList: {}, //角色列表
      selectedRoleId:'',
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      }, //用户列表信息
      userList: [], //用户列表
      total: null,
      dialogVisible: false,
      setRoleDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      }, //新用户的表单数据
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在三到十个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "密码在六到十五个字符之间",
            trigger: "blur",
          },
        ],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
      }, //验证规则对象
      //修改界面的显示和隐藏
      editDialogVisible: false,
      editForm: {}, //用于修改用户信息时对用户信息进行查询
      //修改信息时的表单验证规则
      editFormRules: {
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    // 页码切换
    async handleSizeChange(val) {
      this.queryInfo.pagesize = val;
      const { data: res } = await getUserList(this.queryInfo);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    async handleCurrentChange(val) {
      this.queryInfo.pagenum = val;
      const { data: res } = await getUserList(this.queryInfo);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 将状态改变并发送至服务器进行修改
    async userStateChanged(data) {
      const { data: res } = await upDateUserList(data);
      if (res.meta.status !== 200) {
        this.$message.error("更新失败");
        data.mg_state = !data.mg_state;
      } else {
        this.$message.success("更新成功");
      }
    },
    //用于更新用户数据的函数
    async upDataUserList() {
      const { data: res } = await getUserList(this.queryInfo);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //查找用户
    async queryUser() {
      const { data: res } = await getUserList(this.queryInfo);
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error("获取用户列表失败");
      } else {
        // console.log(res.data.users);
        this.userList = res.data.users;
        this.total = res.data.total;
      }
    },
    //控制添加用户面板的显示
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //重置表单
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },

    // 点击确定按钮添加新的用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          // const { data: res } = await this.$http.post('users', this.addForm)
          const { data: res } = await addUser_axios(this.addForm); //添加用户时post请求使用的是data参数而不是params参数
          if (res.meta.status !== 201) {
            this.$message.error("添加失败");
            console.log(res);
          } else {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            this.upDataUserList(); //更新列表状态
          }
        }
      });
    },
    //展示编辑用户的对话框
    async showEditDialog(id) {
      // console.log(id)
      const { data: res } = await changeUserInfo(id);
      // console.log(res);
      if (res.meta.status != 200) {
        this.$message.error("查询用户信息失败");
      } else {
        this.editForm = res.data;
      }
      this.editDialogVisible = true;
    },
    //关闭用户编辑对话框
    editDiologClose() {
      this.$refs.editFormRef.resetFields();
    },
    //验证用户编辑信息是否合法
    editUserinfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error("输入非法");
          this.editDialogVisible = false;
          return;
        } else {
          //发起修改数据请求
          this.editDialogVisible = false;
          const { data: res } = await upDataChange(this.editForm.id, {
            mobile: this.editForm.mobile,
            email: this.editForm.email,
          });
          if (res.meta.status != 200) {
            this.$message.error("更新失败");
          } else {
            this.$message.success("更新成功");
            this.upDataUserList();
          }
        }
      });
    },
    //删除用户信息
    async removeUserById(id, username) {
      //  console.log(id);
      const confirmResult = await this.$confirm(
        `此操作将永久删除该用户${username}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(confirmResult) 当点击确认时confirmResult得到的是一个值为confirm的字符串,取消是cancel
      if (confirmResult == "confirm") {
        const { data: res } = await removeUser(id);
        if (res.meta.status != 200) {
          this.$message.error("删除失败");
        } else {
          this.$message.success("删除完成");
          this.upDataUserList();
        }
      }
      if (confirmResult == "cancel") {
        return this.$message.info("操作取消");
      }
    },

    //展示分配角色对话框
    async setRole(userInfo) {
      this.userInfo = userInfo;

      //在展示前获取所有的角色列表
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取失败");
      } else {
        this.roleList = res.data;
      }
      this.setRoleDialogVisible = true;
    },

    //点击按钮分配角色
    async saveRoleInfo(){
      if(!this.selectedRoleId)
      {
        this.$message.error("请选择杨分配的角色")
      }
      else{
        const {data: res} = await saveRoleInfo(this.userInfo.id,{
          rid: this.selectedRoleId,
        });
        if(res.meta.status !== 200)
        {
          this.$message.error("角色分配失败");
          console.log(res);
        }
        else{
          
            this.setRoleDialogVisible = false;
            this.$message.success("更新成功");
            this.upDataUserList();
            
        }
      }
    },

    //分配角色表单关闭时触发的事件
    setRoleDialogClosed(){
      this.selectedRoleId= '',
      this.userInfo = {};
    }
  },
  async created() {
    const { data: res } = await getUserList(this.queryInfo);
    // console.log(res)
    if (res.meta.status !== 200) {
      this.$message.error("获取用户列表失败");
    } else {
      // console.log(res.data.users);
      this.userList = res.data.users;
      this.total = res.data.total;
    }
  },
};
</script>

<style lang="less" scoped>
.box-card {
  width: 100%;
}

.el-table {
  margin: 15px 0;
}

.el-pagination {
  margin-top: 15px;
}
</style>
